package sz.szsmk.citizencard.ui.dzsmkfragment;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chenenyu.router.annotation.Route;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.db.DaoSession;
import sz.szsmk.citizencard.db.SysConfDao;
import sz.szsmk.citizencard.dialog.ItemPopWindow;
import sz.szsmk.citizencard.log.L;
import sz.szsmk.citizencard.model.network.bean.response.AdvertisementsRes;
import sz.szsmk.citizencard.model.network.dzbean.res.GetBalanceResponse;
import sz.szsmk.citizencard.model.network.dzbean.res.GetUserInfoRes;
import sz.szsmk.citizencard.model.network.dzbean.res.MessageEvent;
import sz.szsmk.citizencard.model.network.dzbean.res.PreAuthResult;
import sz.szsmk.citizencard.model.network.dzbean.res.SysConf;
import sz.szsmk.citizencard.mvp.BasePresenter;
import sz.szsmk.citizencard.mvp.MineMvpView;
import sz.szsmk.citizencard.mvp.dzsmkpresenter.MinePresenter;
import sz.szsmk.citizencard.ui.dzsmkavtivity.FAQActivity;
import sz.szsmk.citizencard.ui.dzsmkavtivity.MyBankCardActivity;
import sz.szsmk.citizencard.ui.dzsmkavtivity.MyCitizenCardActivity;
import sz.szsmk.citizencard.ui.dzsmkavtivity.PersonInfoEditActivity;
import sz.szsmk.citizencard.ui.dzsmkavtivity.RealNameAuthenticationActivity;
import sz.szsmk.citizencard.ui.dzsmkavtivity.SafeSettingActivity;
import sz.szsmk.citizencard.util.CircleCrop;
import sz.szsmk.citizencard.util.CommonUtils;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.JumpUtils;
import sz.szsmk.citizencard.util.PubUtils;
import sz.szsmk.citizencard.widget.GlobalVariables;

/**
 * Created by chensf on 17/9/30.
 * 电子市民卡我的页面
 */
@Route("dzsmkmine")
public class MineFragment extends AppBaseFragment implements OnFragmentRefresh, MineMvpView, View.OnClickListener {

    ImageView iv_qr_person_pic;
    TextView tv_qr_nick_name;
    TextView tv_qr_phone_number;
    TextView tv_qr_signature;
    TextView tv_qr_mine_balance;
    ImageView home_adaver;


    private String mMyBalance = "--";
    private boolean isChecked;

    //    private User user;
    private GetUserInfoRes user;
    private String mBalanceLitmitMoney = "--";
    private SysConf sysConf;

    TextView tv_investInBalance;

    TextView tv_jianglingjin;

    @Inject
    MinePresenter mMinePresenter;

    @Override
    protected CharSequence getTopTitle() {
        return "";
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        getComponent().inject(this);
        View view = inflater.inflate(R.layout.qr_fragment_mine, container, false);

        iv_qr_person_pic = view.findViewById(R.id.iv_qr_person_pic);

        tv_qr_nick_name = view.findViewById(R.id.tv_qr_nick_name);

        tv_qr_phone_number = view.findViewById(R.id.tv_qr_phone_number);

        tv_qr_signature = view.findViewById(R.id.tv_qr_signature);

        tv_qr_mine_balance = view.findViewById(R.id.tv_qr_mine_balance);

        home_adaver = view.findViewById(R.id.home_adaver );

        tv_investInBalance = view.findViewById(R.id.tv_investInBalance );

        tv_jianglingjin = view.findViewById(R.id.tv_jianglingjin);


        view.findViewById(R.id.tv_qr_edit_person_info).setOnClickListener(this);

        view.findViewById(R.id.btn_qr_recharge).setOnClickListener(this);

        view.findViewById(R.id.bll_qr_my_bank_card).setOnClickListener(this);

        view.findViewById(R.id.bll_qr_my_ctizen_card).setOnClickListener(this);

        view.findViewById(R.id.bll_qr_realname_auth).setOnClickListener(this);

        view.findViewById(R.id.bll_qr_security_set).setOnClickListener(this);

        view.findViewById(R.id.bll_qr_qa).setOnClickListener(this);

        view.findViewById(R.id.bll_qr_contact_us).setOnClickListener(this);

        view.findViewById(R.id.btn_qr_withdrawals).setOnClickListener(this);

        view.findViewById(R.id.bll_qr_my_elec_ctizen_card).setOnClickListener(this);

        view.findViewById(R.id.bll_usuallProblem).setOnClickListener(this);

        view.findViewById(R.id.btn_jljrule).setOnClickListener(this);


        return view;
    }

    public static MineFragment getInstance() {
        MineFragment sf = new MineFragment();
        return sf;
    }

    @Override
    public void onResume() {
        super.onResume();

        PreAuthResult preAuthResult = GlobalVariables.getInstance(getContext()).getPreAuthResult();
        if (preAuthResult == null) {
            return;
        }

        mMinePresenter.getBalance();
        mMinePresenter.getPersonInfo();
        mMinePresenter.getAdvertisements();

//        if (TextUtils.isEmpty(mBalanceLitmitMoney) || mBalanceLitmitMoney.equals("0")) {
        DaoSession daoSession = DaggerApplication.getmDaoSession();
        SysConfDao sysConfDao = daoSession.getSysConfDao();
        List<SysConf> sysConfs = sysConfDao.loadAll();
        int size = sysConfs.size();
        if (null != sysConfs && sysConfs.size() > 0) {
            sysConf = sysConfs.get(0);
            String limitMoney = sysConf.getLimitMoney();
            long balance = CommonUtils.getLong(limitMoney);
            if (balance > 0) {
                mBalanceLitmitMoney = PubUtils.decimalFormatPrice(balance);
            }
        }
//        }

    }

    @Override
    public void onRefresh() {
        PreAuthResult preAuthResult = GlobalVariables.getInstance(getContext()).getPreAuthResult();
        if (preAuthResult == null) {
            return;
        }

        mMinePresenter.getBalance();
        mMinePresenter.getPersonInfo();


    }


    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        isChecked = true;
        tv_qr_mine_balance.setText(String.format(getString(R.string.qr_mine_balance), mMyBalance));


        //mMinePresenter.getBalance();
        //mMinePresenter.getPersonInfo();
    }

    @Override
    protected BasePresenter[] initPresenters() {
        return new BasePresenter[]{mMinePresenter};
    }

    PreAuthResult preAuthResult;


    public void onClickView(View v) {
        preAuthResult = GlobalVariables.getInstance(getContext()).getPreAuthResult();
        String json = new Gson().toJson(preAuthResult);
        L.e(Constant.TAG, "登录信息+" + json);
        if (preAuthResult == null) {
            PubUtils.popTipOrWarn(getContext(), "认证失败，正常功能无法使用");
            return;
        }
        String status = preAuthResult.getUserStatus();
        if (R.id.tv_qr_edit_person_info == v.getId()) {//编辑个人资料
            launch(PersonInfoEditActivity.class);
        } else if (R.id.btn_qr_withdrawals == v.getId()) {
            if (Constant.QUERY_QR_RESULT_NO_AUTH.equals(status)) { //实名认证
                PubUtils.popTipOrWarn(getContext(), "请先进行实名认证");
                Intent intent = new Intent(getActivity(), RealNameAuthenticationActivity.class);
                intent.putExtra("isRealName", "0");
                startActivity(intent);
            } else if (Constant.QUERY_QR_RESULT_NO_PAY_PWD_SET.equals(status)) { //设置密码
                PubUtils.popTipOrWarn(getContext(), "请先设置交易密码");
                launch(SafeSettingActivity.class);
            } else {
//                launch(WithdrawalsActivity.class);
            }
        } else if (R.id.btn_qr_recharge == v.getId()) { //充值
            if (Constant.QUERY_QR_RESULT_NO_AUTH.equals(status)) { //实名认证
                PubUtils.popTipOrWarn(getContext(), "请先进行实名认证");
                Intent intent = new Intent(getActivity(), RealNameAuthenticationActivity.class);
                intent.putExtra("isRealName", "0");
                startActivity(intent);
            } else if (Constant.QUERY_QR_RESULT_NO_PAY_PWD_SET.equals(status)) { //设置密码
                PubUtils.popTipOrWarn(getContext(), "请先设置交易密码");
                launch(SafeSettingActivity.class);
            } else {
                Bundle bundle = new Bundle();
                bundle.putString(Constant.TYPE,mBalanceLitmitMoney);
                JumpUtils.jumptoNatvie(getActivity(),"RechargeActivity",0,bundle);
//                launch(RechargeActivity.class);
            }
        }  else if (R.id.bll_qr_my_bank_card == v.getId()) { //我的银行卡
            if (Constant.QUERY_QR_RESULT_NO_AUTH.equals(status)) {
                PubUtils.popTipOrWarn(getContext(), "请先进行实名认证");
                Intent intent = new Intent(getActivity(), RealNameAuthenticationActivity.class);
                intent.putExtra("isRealName", "0");
                startActivity(intent);
            } else {
                launch(MyBankCardActivity.class);
            }
        } else if (R.id.bll_qr_my_ctizen_card == v.getId()) { // 我的市民卡
            launch(MyCitizenCardActivity.class);

        } else if (R.id.bll_qr_realname_auth == v.getId()) { //实名认证
            Intent intent1 = new Intent(getActivity(), RealNameAuthenticationActivity.class);

            intent1.putExtra("isRealName", user.getData().getIsRealName());

            startActivity(intent1);
        } else if (R.id.bll_qr_security_set == v.getId()) { //安全设置
            if (Constant.QUERY_QR_RESULT_NO_AUTH.equals(status)) {
                PubUtils.popTipOrWarn(getContext(), "请先进行实名认证");
                Intent intent = new Intent(getActivity(), RealNameAuthenticationActivity.class);
                intent.putExtra("isRealName", "0");
                startActivity(intent);
            } else {
                launch(SafeSettingActivity.class);
            }
        } else if (R.id.bll_qr_qa == v.getId()) { //常见问题
            launch(FAQActivity.class);
        } else if (R.id.bll_qr_contact_us == v.getId()) { //联系我们
            showHelpPopDialog(v);
//            if (sysConf != null) {
//                showHelpPopDialog(v);
//            }
        } else if (R.id.bll_qr_my_elec_ctizen_card == v.getId()) {

        }else if(R.id.bll_usuallProblem==v.getId()){
            //常见问题
            launch(FAQActivity.class);
        }else if(R.id.btn_jljrule == v.getId()){
            //奖励金规则
            String url = "https://newapp.szsmk.com/images/app/bonus_intro.html";
            Bundle bundle = new Bundle();
            bundle.putString("url", url);
            bundle.putString(Constant.TITLE, "奖励金规则");
            JumpUtils.jumptoNatvie(getActivity(), "webView", 0, bundle);
        }
    }

    private void showHelpPopDialog(View v) {
        DaoSession daoSession = DaggerApplication.getmDaoSession();
        SysConfDao sysConfDao = daoSession.getSysConfDao();
        final List<SysConf> sysConfs = sysConfDao.loadAll();
        ItemPopWindow.PopItem popItem = new ItemPopWindow.PopItem();
//        if(sysConfs.size()>0){
            popItem.setName("客服电话 ：" + "(0512)962026");
            popItem.setPosition(0);
//        }
        List<ItemPopWindow.PopItem> popItems = new ArrayList<>();
        popItems.add(popItem);

        ItemPopWindow popWindow = new ItemPopWindow(getActivity(), new ItemPopWindow.OnItemClickListener() {
            @Override
            public void onItemClick(ItemPopWindow.PopItem popItem) {
                if (0 == popItem.getPosition()&&sysConfs.size()>0) {
                    Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + sysConfs.get(0).getServiceNumber()));
//                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else if(0 == popItem.getPosition()&&sysConfs.size()==0){
                    Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "0512962026"));
                    startActivity(intent);
                }
            }
        }, popItems, -1, Color.parseColor("#5080D8"));

        popWindow.showAtLocation(v, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);


    }

    @Override
    public void onEvent(MessageEvent event) {
        if (MessageEvent.CODE_UPDATE_USERINFO_SUCCESS == event.getCode()) {
            mMinePresenter.getPersonInfo();
        } else if (MessageEvent.CODE_UPDATE_BALANCE_SUCCESS == event.getCode()) {
            mMinePresenter.getBalance();
        }
    }

    @Override
    public void onGainBalance(GetBalanceResponse sysResponse) {
        GetBalanceResponse.DataBean bean  = sysResponse.getData();
        mMyBalance = PubUtils.decimalFormatPrice(bean.getBonus()+bean.getMoney());
        tv_qr_mine_balance.setText(String.format(getString(R.string.qr_mine_balance), mMyBalance));

        tv_investInBalance.setText( bean.getMoneyStr() +"");
        tv_jianglingjin.setText(bean.getBonusStr()+"");


    }

    @Override
    public void onGainBalanceFail() {
        tv_qr_mine_balance.setText("--元");
    }

    @Override
    public void onGainPersonInfo(GetUserInfoRes user) {
        this.user = user;
        GetUserInfoRes.DataBean data = user.getData();
        String nickName = data.getNickName();
        tv_qr_nick_name.setText(data.getRealName());
        tv_qr_phone_number.setText(data.getPhoneNumber());

        tv_qr_signature.setText(data.getPersonalSignature());
        //Glide.with(MineFragment.this).load(user.getPhotoUrl()).placeholder(R.mipmap.qr_ic_launcher).error(R.mipmap.qr_ic_launcher).into(iv_qr_person_pic);

        Glide.with(getContext()).load(data.getPhotoUrl()).placeholder(R.drawable.qr_default_avatar).error(R.drawable.qr_default_avatar).transform(new CircleCrop(getContext())).into(iv_qr_person_pic);
        PreAuthResult preAuthResult = GlobalVariables.getInstance(getContext()).getPreAuthResult();
        if (!data.getIsRealName().equals("0") && preAuthResult.getUserStatus().equals(Constant.QUERY_QR_RESULT_NO_AUTH)) {
            preAuthResult.setUserStatus(Constant.QUERY_QR_RESULT_NO_PAY_PWD_SET);
            GlobalVariables.getInstance(getContext()).setPreAuthResult(getContext(), preAuthResult);
        }
    }

    @Override
    public void getAdvertisementsResult(AdvertisementsRes advertisementsRes) {
        AdvertisementsRes.DataBean bean = advertisementsRes.getData();
        if(bean.getDetail()!=null && bean.getDetail().get(0)!=null){
            Glide.with(getActivity())
                    .load(bean.getDetail().get(0).getImgUrl())
                    .into(home_adaver);
            home_adaver.setOnClickListener(view -> {
                int mNendHeader = 0;
                String link_url = bean.getLinkUrl();
                String need_header = bean.getNeedHeader();
                if (need_header != null) {
                    mNendHeader = Integer.valueOf(need_header).intValue();
                }
                String sys_label = bean.getDetail().get(0).getSysLabel();
                //准备删除
//                JumpThirdView.baseToJumpViewForDZSMK(getContext(), link_url, sys_label, mNendHeader, preAuthResult);

            });
            home_adaver.setVisibility(View.VISIBLE);
        }else{
            home_adaver.setVisibility(View.GONE);
        }


    }

    @Override
    public void onClick(View v) {
        onClickView(v);
    }
}
